package com.fanjia.taobao.common.exceptionhandler;


import com.fanjia.taobao.common.util.ResEntity;
import com.fanjia.taobao.common.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import sun.security.validator.ValidatorException;

import javax.xml.ws.http.HTTPException;
import java.io.IOException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(RuntimeException.class)
    public ResEntity doHandleRuntimeException(RuntimeException e) {
        e.printStackTrace();//控制台输出
        log.error("exception msg {}" + e.getMessage());
        if (e instanceof DuplicateKeyException) {
            return ResponseUtil.error(400, "手机号已注册");
        } else {

            return ResponseUtil.error(400, "系统维护中");
        }

    }


    @ExceptionHandler(Exception.class)
    public ResEntity doHandleException(Exception e) {
        e.printStackTrace();//控制台输出
        log.error("exception msg {}" + e.getMessage());


        if (e instanceof IOException) {
            return ResponseUtil.error(400, "发送验证码失败");
        } else if (e instanceof HTTPException) {
            return ResponseUtil.error(400, "发送验证码失败");
        } else if (e instanceof DuplicateKeyException) {
            return ResponseUtil.error(400, "手机号已注册");
        } else {
            return ResponseUtil.error(400, "系统维护中");
        }

    }


    @ExceptionHandler(MyException.class)
    public ResEntity doHandleValidatorException(MyException e) {
        e.printStackTrace();//控制台输出
        log.error("exception msg {}", e.getMsg());

        if (e instanceof MyException) {
            return ResponseUtil.error(e.getCode(), e.getMsg());
        } else {
            return ResponseUtil.error(400, "系统维护中");
        }

    }


}